﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Service;
using DeHeng_Mes.Utils;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Controls.Primitives;

namespace DeHeng_Mes.Thread
{
    public class MesDataPush
    {
        OrderDao orderDao = new OrderDao();
        ViewDao viewDao = new ViewDao();
        QueryDataDao dataDao = new QueryDataDao();

        public async Task pushTask()
        {
            Tools.ProduceLogText("Mes数据推送线程启动成功！");

            while (true)
            {
                await Task.Delay(1000);

                try
                {
                    // 查询工单绑定的工件码
                    List<OrderTrace> orderTraces = orderDao.QueryOrderTrace();

                    if (orderTraces?.Count > 0)
                    {
                        //拿到件绑定工单未推送的数据
                        List<OrderTrace> partPushStatuses = orderTraces.Where(x => x.PartPushStatus.Equals("0")).ToList();

                        //拿到过站数据未推送的数据
                        List<OrderTrace> stationPushStatuses = orderTraces.Where(x => x.StationPushStatus.Equals("0")).ToList();

                        foreach (var orderTrace in partPushStatuses)
                        {
                            //唯一标识
                            string code = Tools.GetHashCodeFromPushMes(orderTrace.OrderId, orderTrace.TraceId, orderTrace.CreateTime);

                            int partCount = 1;

                            string dataDtlId = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, partCount.ToString(), orderTrace.CreateTime);

                            // 推送单件上件绑定数据
                            int count = viewDao.PushPartData(new LineMesData()
                            {
                                OrderId = orderTrace.OrderId,
                                TraceId = orderTrace.TraceId,
                                CreateTime = orderTrace.CreateTime,
                                DataFrom = "德恒W03左右门槛线",
                                DataId = code,
                            });

                            if (count > 0)
                            {
                                orderDao.UpdatePartPushStatus(orderTrace.OrderId, orderTrace.TraceId);
                            }
                        }

                        foreach (var orderTrace in stationPushStatuses)
                        {
                            List<PartProcess> partProcesses = await orderDao.GetProcessData(orderTrace.TraceId);

                            partProcesses = partProcesses.Where(x => !string.IsNullOrEmpty(x.Result) && (x.IsSave == null || !x.IsSave.Equals("1"))).ToList();

                            string code = Tools.GetHashCodeFromPushMes(orderTrace.OrderId, orderTrace.TraceId, orderTrace.CreateTime);

                            try
                            {
                                if (partProcesses?.Count > 0)
                                {
                                    // 推送数据
                                    foreach (PartProcess partProcess in partProcesses)
                                    {
                                        // 获取工站对应工序
                                        string operations = MappingTable.GetOperationId(partProcess.Station);

                                        List<string> operationList = operations.Split(',').ToList();

                                        List<string> list = partProcess.Result.Split(',').ToList();

                                        for (int i = 0;i < operationList.Count;i++)
                                        {
                                            string stationCode = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, operationList[i], partProcess.EndTime);

                                            // 拼接过站数据进行推送
                                            int v = await viewDao.PushStationData(new LineMesDataTrace()
                                            {
                                                DataId = code,
                                                DataTraceId = stationCode,
                                                Station = partProcess.Station,
                                                Process = operationList[i],
                                                Result = list[i],
                                                CreateTime = partProcess.EndTime,
                                                StartTime = partProcess.StartTime,
                                                EndTime = partProcess.EndTime,
                                                DataFrom = "德恒W03左右门槛线",
                                                UserId = "",
                                            }, partProcess.TraceId);
                                        }

                                        // 更新工站表状态
                                        bool isOk = orderDao.UpdateStationSaveStatus(partProcess.Id, partProcess.TraceId);

                                        // 如果末工序更新工单表状态
                                        if (partProcess.Station.Contains("180"))
                                        {
                                            await orderDao.UpDateOrderTraceSave(partProcess.TraceId, orderTrace.OrderId);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Tools.ProduceLogTextError($"推送过站数据与投料数据失败，原因是{ex.Message}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"组装或者推送工厂Mes数据失败，原因是{ex.Message}");
                }
            }
        }

        public async Task CodePushTask()
        {
            Tools.ProduceLogText("明暗码推送线程启动成功！");

            while (true)
            {
                await Task.Delay(1000);

                try
                {
                    List<TracePoint> tracePoints = new List<TracePoint>();
                    //拿到未推送的明暗码
                    for (int i = 0; i < 10; i++)
                    {
                        
                        List<TracePoint> pointStatus = orderDao.QueryPoint("1",i);

                        tracePoints.AddRange(pointStatus);

                    } 

                    if (tracePoints?.Count > 0)
                    {

                        foreach (var item in tracePoints)
                        {
                            string dataDtlId = Tools.GetHashCodeFromPushMes(item.Code, item.PointCode, item.CreateTime);

                            bool isOk = orderDao.UpdatePointSaveStatus(item.Id, item.Code);

                            int count = viewDao.PushPointData(new LineMesDataBarcodeRelation()
                            {
                                Id = dataDtlId,
                                TraceNo = item.Code,
                                ViewCode = item.PointCode,
                                CreateTime = item.CreateTime,
                                DataFrom = "德恒W03左右门槛线",
                                EqptId = item.Station,
                                DataType = "normal"
                            });

                        }

                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"推送明暗码失败，原因是{ex.Message}");
                }
            }
        }

        public async Task FDSPushTask()
        {
            Tools.ProduceLogText("FDS推送线程启动成功！");

            while (true)
            {
                await Task.Delay(1000);

                try
                {
   

                  
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"推送FDS数据失败，原因是{ex.Message}");
                }
            }
        }

        public static string GetBetweenDashes( string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            // 正则表达式：匹配两个-之间的任何非-字符
            var match = Regex.Match(input, @"-(.*?)-");
            return match.Success ? match.Groups[1].Value : string.Empty;
        }
    }
}
